/*
 * @(#)NewsService.java
 * 2012-9-4 下午06:00:52
 * 
 *
 * Copyright (c) 2018-2028, HangZhou QiYun InfoTech Co.,Ltd. .
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.qyxx.platform.sysmng.notice.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.collect.Lists;
import com.qyxx.platform.common.orm.Page;
import com.qyxx.platform.common.orm.PropertyFilter;
import com.qyxx.platform.sysmng.accountmng.dao.UserDao;
import com.qyxx.platform.sysmng.accountmng.entity.Organization;
import com.qyxx.platform.sysmng.accountmng.entity.User;
import com.qyxx.platform.sysmng.notice.dao.NewsDao;
import com.qyxx.platform.sysmng.notice.dao.VisitorDao;
import com.qyxx.platform.sysmng.notice.entity.News;
import com.qyxx.platform.sysmng.notice.entity.Visitor;


/**
 *  
 *  @author ly
 *  @version 1.0 2012-9-4 下午06:00:52
 *  @since jdk1.6 
 */
@Component
@Transactional
public class NewsManager {
	private static final String FIND_NEWS_BY_USERID="select a from News a where a.createUser = ?";
	private static final String FIND_NEWS_BY_STATUS="select a from News a where  a.status = ? and  a.id in " +
			"(select a.id from News a inner join a.organizationList b  where b.id in (select c.id from Organization c where c.organizationCode in (:list)))";
	private static final String FIND_VISITORS_BY_RELEVANCEID = "SELECT DISTINCT USER_ID FROM SYS_VISITOR WHERE RELEVANCE_ID = :relevanceId";
	
	private NewsDao newsDao;
	private VisitorDao visitorDao;
	private UserDao userDao;
	
	@Autowired
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	@Autowired
    public void setNewsDao(NewsDao newsDao) {
		this.newsDao = newsDao;
	}
    
	public NewsDao getNewsDao() {
		return newsDao;
	}
	
	@Autowired
	public void setVisitorDao(VisitorDao visitorDao) {
		this.visitorDao = visitorDao;
	}
	
	public void saveNews(News news,Long userId,String orgIds){
		//修改一条新闻
		Long nId = news.getId();
		if(news.getId()!=null){
			news.setLastUpdateUser(userId);
			news.setLastUpdateTime(new Date());
			newsDao.deleteByNewsId(nId);
		}else{//新增一条新闻
			news.setCreateUser(userId);
			news.setCreateTime(new Date());
		}
		
		newsDao.save(news);
		nId = news.getId();
		if (StringUtils.isNotBlank(orgIds)){//再添加记录
               String organizationIds[] = orgIds.split(",");
			for (String organizationId : organizationIds) {
				Long orgId = Long.valueOf(organizationId);
				newsDao.saveNewToOrg(orgId,nId);
			}
		}
    }
	
	/**
	 * 更新新闻中的附件
	 * 
	 * @param newsId
	 * @param attachId
	 */
	public void updateNews(Long newsId,Long attachId){
		News news=newsDao.get(newsId);
		news.setAtmId(attachId);
	}
	
	
	/**
	 * 修改新闻的发布状态
	 * 
	 * @param newsId
	 * @param userId
	 * @param status
	 */
	public void repealNews(final Long newsId,Long userId,String status){
		News news=newsDao.get(newsId);
		news.setLastUpdateUser(userId);
		news.setLastUpdateTime(new Date());
		news.setStatus(status);
	}
    
   
	/**
	 * 查询新闻列表
	 * 
	 * @param page
	 * @param filters
	 * @return
	 */
	@Transactional(readOnly = true)
    public  Page<News> findNewsList(Page<News> page, List<PropertyFilter> filters){
		return this.preHandlePage(newsDao.findPage(page, filters));
    }
	
	
	/**
	 * 分页查询用户接受到的通知
	 * 
	 * @param page
	 * @param userId
	 * @param filters
	 * @return
	 */
	public Page<News> findNewsToUserList(Page<News> page, User user, List<PropertyFilter> filters){
		List<Object> paramList = Lists.newArrayList();
		paramList.add(News.STATUS_1);
		String orgCode = user.getOrganization().getOrganizationCode();
		List<String> codeList = Organization.getSplitCodeList(orgCode);
		StringBuffer sb = new StringBuffer();
		List<String> strList = new ArrayList<String>();
		for(String o : codeList) {
			strList.add("?");
			paramList.add(o);
		}
		sb.append(StringUtils.join(strList, ","));
		String sql = StringUtils.replace( FIND_NEWS_BY_STATUS, ":list",sb.toString());
		return this.preHandlePage(newsDao.findPage(sql, page, filters, paramList.toArray()));
	}
    
    public void deleteNews(Long[] ids){
    	for(Long id : ids){
    		newsDao.delete(id);
    	}
    	
    }
    
    /**
     * 根据id查询一条新闻
     * 
     * @param id
     * @return
     */
    public News findNewsById(Long id){
    	News entity = newsDao.get(id);
		return entity;
    }
    
    
    /**
     * 查看新闻时点击率+1
     * @param id
     * @return
     */
    public News addNewsClickCount(Long id){
    	News entity = newsDao.get(id);
    	if(entity.getClickCount()==null){
    		int count=0;
        	entity.setClickCount(new Long (count+1));
    	}else{
    		Long clickCount=entity.getClickCount();
    		entity.setClickCount(clickCount+1);
    	}
		return this.preHandleObj(entity);
    }
  

    /**
	 * 查询当前用户发的所有新闻
	 * @param page
	 * @param userId
	 * @return
	 */
	public Page<News> findNewsListByUserId(Page<News> page,Long userId){
		return newsDao.findPage(page,FIND_NEWS_BY_USERID,userId);
	}

	/**
	 * 新增访问者记录
	 * @param id
	 * @param userId
	 * @return
	 */
	public void addVisitor(Long id, Long userId) {
		// TODO Auto-generated method stub
		Visitor visitor = new Visitor();
		visitor.setRelevanceId(id);
		visitor.setUserId(userId);
		visitor.setVisitTime(new Date());
		visitorDao.save(visitor);
	}

	/**
	 * 分页查询当前新闻的所有访问者
	 * @param page
	 * @param filters
	 * @return
	 */
	public Page<Visitor> findVisitorsList(Page<Visitor> pager,
			List<PropertyFilter> filters) {
		// TODO Auto-generated method stub
		pager.setOrder(Page.DESC);
		pager.setOrderBy("id");
		return preHandleVisitorPage(visitorDao.findPage(pager, filters));
	}

	/**
	 * 查询当前新闻的zise条最近访问者
	 * @param id
	 * @param size
	 * @return
	 */
	public List<Map<String, Object>> findVisitorsList(Long id, Integer size) {
		// TODO Auto-generated method stub
		Page<Object> page = new Page<Object>();
		page.setPageNo(1);
		page.setPageSize(size);
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("relevanceId", id);
		return preHandleVisitorList(visitorDao.findDataMapListBySql(FIND_VISITORS_BY_RELEVANCEID, param, page));
	}
	
	
	/**
	 * 处理Page对象，翻译字段
	 * 
	 * @param page
	 * @return
	 */
	public Page<News> preHandlePage(Page<News> page) {
		List<News> list = page.getResult();
		if(list != null) {
			for(News n : list) {
				n.setCreateUserCaption(userDao.getUserNameById(n.getCreateUser()));
			}
		}
		return page;
	}
	
	/**
	 * 预处理对象，翻译字段
	 * 
	 * @param obj
	 * @return
	 */
	public News preHandleObj(News obj) {
		if(obj != null) {
			obj.setCreateUserCaption(userDao.getUserNameById(obj.getCreateUser()));
		}
		return obj;
	}
	
	/**
	 * 处理Page对象，翻译字段
	 * 
	 * @param page
	 * @return
	 */
	public Page<Visitor> preHandleVisitorPage(Page<Visitor> page) {
		List<Visitor> list = page.getResult();
		if(list != null) {
			for(Visitor n : list) {
				n.setUserName(userDao.getUserNameById(n.getUserId()));
			}
		}
		return page;
	}
	
	/**
	 * 处理Page对象，翻译字段
	 * 
	 * @param page
	 * @return
	 */
	public List<Map<String,Object>> preHandleVisitorList(List<Map<String,Object>> list) {
		if(list != null) {
			for(Map<String,Object> n : list) {
				Long uid = ((Number)n.get("USER_ID")).longValue();
				n.put("userName", userDao.getUserNameById(uid));
			}
		}
		return list;
	}

}
